package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.service.goods.SpuService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;

//商品索引数据删除
@Service
public class IndexDeleteMessageConsumer implements MessageListener {
    @Reference
    private SpuService spuService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void onMessage(Message message) {
        String spuId = new String(message.getBody());
        Goods goods = spuService.findGoodsById(spuId);
        List<Sku> skuList = goods.getSkuList();

        /*

        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client).
                filter(QueryBuilders.matchQuery("spuId", spuId)).source("sku").get();

        long deleted = response.getDeleted();//获取删除的记录数量
        System.out.println(deleted);*/

        for (Sku sku : skuList) {
            try {
                DeleteRequest deleteRequest=new DeleteRequest("sku","doc",sku.getId());
                DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
                System.out.println(deleteResponse);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    restHighLevelClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
